package com.sk.coin.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 上线文工具类
 * @author: songkun
 * @date: 2022/3/5
 */
public class ContextUtil {

    /**
     * 获取上线文中的用户id
     * @return userId
     */
    public static Long getUserId() {
        String strUserId = getStrUserId();
        if (StringUtils.isNotEmpty(strUserId)) {
            return Long.valueOf(strUserId);
        }
        return null;
    }

    public static String getStrUserId() {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal != null) {
                return principal.toString();
            }
        }
        return null;
    }

    /**
     * 获取安全的上下文
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取Request对象
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

}
